package org.springleaf.utils;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

/**
 * spring Bean Factory工具类
 * @author leaf
 */
@SuppressWarnings("unchecked")
public class SpringBeanFactoryUtils implements BeanFactoryAware {

	private static BeanFactory beanFactory;

	public void setBeanFactory(BeanFactory beanFactory) {
		SpringBeanFactoryUtils.beanFactory = beanFactory;
	}
	
	/**
	 * 通过Class类型得到spring bean
	 */
	public static <T> T getBean(Class<T> classz) {
		return (T) beanFactory.getBean(classz);
	}

	/**
	 * 通过id得到spring bean
	 */
	public static <T> T getBean(String name) {
		if(containsBean(name)){
			return (T) beanFactory.getBean(name);
		}else{
			try {
				throw new Exception("Can't not find Spring Bean : [" + name + "]");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static boolean containsBean(String name) {
		return beanFactory.containsBean(name);
	}

	public static BeanFactory getBeanFactory() {
		return beanFactory;
	}
}